<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class M_users extends MY_Model {
	
	private $last_insert_id;
	/* 	
		-------------------------------------------------------------------
		add_user
		12-6-12
		perry
		-------------------------------------------------------------------
		Adds a user on the system
		
		Returns true if add success
		Returns false if add unsuccessful
	*/
	public function add_user($attrib){
		$v = (object) $attrib;
		$hashed_password = $this->hash_password($v->hashed_password);
		
		$user_data = array(
				'username' => $v->username,
				'hashed_password' => $hashed_password,
				'userType' => $v->userType,
				'userStatus' => $v->userStatus,
				'created_at' => NOW,
		);
		$this->db->insert('users', $user_data);

		$this->last_insert_id = $this->db->insert_id();
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	}
	
	
	/* 	
		-------------------------------------------------------------------
		verify_user
		12-6-12
		perry
		-------------------------------------------------------------------
		 Verifies if an existing user is present in the system and checks their login credentials
		
		Returns false if credentials are invalid or userstatus is not active
		Returns true if credentials are valid
	*/
	public function verify_user($attrib,$usertype)
	{
		unset($attrib['captcha_text']);
		unset($attrib['form_input_token']);
		unset($attrib['backstage_login']);
		
		$v = (object) $attrib;
		
		$username_filter = $this->db->escape_str($v->username);
		$password_filter = $this->db->escape_str($v->password);
		
		
		$this->db->where('username', $username_filter);
		$query = $this->db->get('users');
		
		if($query->num_rows() >= 1 && $query->row()->userStatus == 'active' && $query->row()->userType == $usertype)
		{
			$row = $query->row();

			if($this->validate_password($row->hashed_password, $password_filter))
			{
				$emp = $this->db->select('first_name,last_name,middle_name,emp_id')
								->where('id',$row->id)
								->get('employees');

				// pd($emp->row());
				if($emp->num_rows() >= 1)
				{
					$fname = $emp->row()->first_name;
					$lname = $emp->row()->last_name;
					$mname = $emp->row()->middle_name;
					$emp = $emp->row()->emp_id;
				}else{
					$fname = '______';
					$lname = '______';
					$mname = '______';
					$emp = 0;
				}
				
				$userType = $row->userType=='vice-principal'?'vice_principal':$row->userType;
				
				$userdata = array(
					'userid' => $row->id,
					'username' => $row->username,
					'userType' => $userType,
					'e_f_name' => $fname,
					'e_l_name' => $lname,
					'e_m_name' => $mname,
					'logged_in' => TRUE,
					'loc_emp_id' => $emp
				);
				$this->session->set_userdata($userdata);
				return true;
			}else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
			
	}
	
	
	/* 	
		-------------------------------------------------------------------
		hash_password
		-------------------------------------------------------------------
	*/
	public function hash_password($password)
    {
        $this->load->helper('passwordcompat');
		return password_hash($password,PASSWORD_BCRYPT);
    }

	/* 	
		-------------------------------------------------------------------
		validate_password
		-------------------------------------------------------------------
	*/
	public function validate_password($hashed_password, $password)
    {
		$this->load->helper('passwordcompat');
        return password_verify($password, $hashed_password);
    }
	
	/*
	--------------------------------------------------------------------------
	get_all_users
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	if parameter is false gets all users from db
	if parameter exists gets specific id from parameter
	*/
	
	
	
	public function get_all_users($id = FALSE)
	{
		if($id == FALSE){
			$query = $this->db->get('users');		
		}else{
			$query = $this->db->where('id',$id)->get('users');	
		}
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	/*
	--------------------------------------------------------------------------
	update_users
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	@param data = array
	updates user info
	*/	
	
	public function update_user($id,$data)
	{
		$this->db->set($data)->where('id',$id)->update('users');
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	}
	

	/*
	--------------------------------------------------------------------------
	change_pass
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	@param newpass
	updates password
	*/	
	
	public function change_pass($newpassword,$id)
	{
		$newpassword = $this->hash_password($newpassword);
		if($this->db->set('hashed_password',$newpassword)->where('id',$id)->update('users')){
			return TRUE;
		}else{
			return FALSE;
		}
	}
	
	/*
	--------------------------------------------------------------------------
	verify_password
	12-6-2012
	tom
	--------------------------------------------------------------------------
	@param id
	@param old password
	checks password from database and matches from user input
	*/	
	public function verify_password($password,$id)
	{
		$data = $this->db->select('hashed_password')->where('id',$id)->get('users');
		
		$h_pass = $data->num_rows() >=1 ? $data->row()->hashed_password : FALSE;
		
		if($this->validate_password($h_pass,$password)){
			return TRUE;	
		}else{
			return FALSE;
		}
	}

		
	public function destroy($id)
	{
		$this->db->update('status','inactive')->where('id',$id)->update('users');
		return $this->db->affected_rows() > 0 ? TRUE : FALSE;
	}
		
	
	function delete_user($user_id){
		$this->db->where('id', $user_id)->delete('users');
		return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
	}
	
	
	public function register_user($user_data, $profile_data)
	{
		$user_data['created_at'] = NOW;
		$user_data['userType'] = 'student';
		$user_data['userStatus'] = 'active';
		$profile_data['created'] = NOW;
		
		$this->db->insert('users', $user_data);
		$last_insert_id = $this->db->insert_id();
		if($this->db->affected_rows() >= 1)
		{
			$profile_data['user_id'] = $last_insert_id;
			$this->db->insert('profiles', $profile_data);
			$this->last_insert_id = $this->db->insert_id();
			if($this->db->affected_rows() >= 1){
				return TRUE;
			}
			else {
				$this->db->where('user_id', $last_insert_id)->delete('users');
				return FALSE;	
			}
		}
		else
			return false;
	}

	public function get_last_insert_id()
	{
		return $this->last_insert_id;
	}
	
	// Function that accepts a string parameter $username and an int $id. Checks if another username with a different id is in the database.
	// If there are others present, FALSE is returned and TRUE otherwise.
	public function check_duplicates($username, $user_id)
	{
		$sql = "SELECT * FROM users WHERE username = ? AND id != ?";
		$query = $this->db->query($sql, array($username, $user_id));
		return $query->num_rows() > 0 ? FALSE : TRUE;
	}
		
	function get_user_data($parameter, $data)
	{
		if($parameter == 'id')
		{
			$sql = "SELECT * FROM users WHERE id = ?";
		}else if ($parameter == 'username')
		{
			$sql = "SELECT * FROM users WHERE username = ?";
		}
		
		$query = $this->db->query($sql, array($data));
		return $query->num_rows() > 0 ? $query->result() : FALSE;
	}
	
	function get_user_data_empid($emp_id)
	{
		$sql = "SELECT users.id, username, last_name, first_name, middle_name FROM users
				JOIN employees ON users.id = employees.id
				WHERE employees.emp_id = ?";
		$query = $this->db->query($sql, array($emp_id));
		return $query->num_rows() > 0 ? $query->row() : FALSE;
	}
	
	public function save_temporary_users($user,$profile)
	{
		$user_input['username'] = $user['username_username'];
		$user_input['hashed_password'] = $this->hash_password($user['password_password']);
		$user_input['userType'] = $user['usertype'];
		$user_input['userStatus'] = 'active';
		$user_input['created_at'] = NOW;
		
		$profile_input['last_name'] = $profile['lastname'];
		$profile_input['first_name'] = $profile['firstname'];
		$profile_input['middle_name'] = $profile['middlename'];
		$profile_input['role'] = $user['usertype'];
		$profile_input['userStatus'] = 'active';
		$profile_input['given_id'] = $user['username_username'];
		
		
		
		$this->db->insert('users',$user_input);
		$this->last_insert_id = $this->db->insert_id();
		
		if($this->db->affected_rows() >= 1)
		{
			$profile_input['id'] = $this->last_insert_id;
			$this->db->insert('employees',$profile_input);
			$this->last_insert_id = $this->db->insert_id();
			
			if($this->db->affected_rows()>=1)
			{
				return TRUE;
			}else{
				$this->db->where('emp_id',$this->last_insert_id)->delete('employees');
				return FALSE;
			}
		}else{
			$this->db->where('id',$this->last_insert_id)->delete('users');
			return FALSE;
		}
	}

	public function create_parent_login($data)
	{
		$for_insert['username'] = $data['parent_username'];
		$for_insert['hashed_password'] = $data['parent_password'];
		$for_insert['userType'] = 'user';
		$for_insert['userStatus'] = 'active';
		$for_insert = (object)$for_insert;

		$res = $this->add_user($for_insert);


		if($res)
		{


			foreach($data['children'] as $k => $v)
			{
				$id = explode('-',$v);
				$input[$k]['p_id'] = $id[0];
				$input[$k]['e_id'] = $id[1];
				$input[$k]['ay_id'] = $this->c_sy->id;
				$input[$k]['user_id'] = $this->last_insert_id;
			}

			$this->db->insert_batch('parent_child',$input);

			$finished['_username'] = $data['parent_username'];
			$finished['_password'] =  $data['parent_password'];
			$finished['_useremails'][] = (object)['email'=>$data['parent_email']];

			return $this->db->affected_rows() >=1 ? $finished : FALSE;
		}else{
			return FALSE;
		}
	}
	
	public function add_student_to_parent_login($user_id, $children)
	{
		if($user_id && $children)
		{
			foreach($children as $k => $v)
			{
				$id = explode('-',$v);
				$input[$k]['p_id'] = $id[0];
				$input[$k]['e_id'] = $id[1];
				$input[$k]['ay_id'] = $this->c_sy->id;
				$input[$k]['user_id'] = $user_id;
			}

			$this->db->insert_batch('parent_child',$input);

			return $this->db->affected_rows() >=1 ? TRUE : FALSE;
		}else{
			return FALSE;
		}
	}

	/**
	 * Update Parent Login
	 *
	 * Update Parent username and password
	 * @param post array
	 */
	public function update_parent_login($post, $id)
	{
		$rs = $this->db->select('username')->where('id', $id)->get('users')->row();

		if($rs){

			$data = false;

			if(isset($post['inc_username'])){
				if($rs->username !== $post['parent_username']){

					/* Update User name */
					$data['username'] = $post['parent_username'];
					$rs_u = $this->update_user($id, $data);
				}
			}

			if(isset($post['inc_password'])){
				$password = $post['parent_password'];
				$cpassword = $post['parent_cpassword'];
				if($password === $cpassword){

					/* Update Password */
					$rs_up = $this->udpate_users_passwod($id, $password);
				}
			}

			return true;
		}

		return false;
	}
	
	public function count_parent_login()
	{
		$sql = 'SELECT count(id) as total
				  FROM users
				  WHERE userType = "user"
				  AND userStatus = "active"';
		$res = $this->db->query($sql);
		return $res->num_rows() >=1 ? $res->row()->total : 0;
	}
	
	public function get_parent_login($start,$limit, $id = false)
	{
		$sql = "SELECT DISTINCT pc.user_id, u.username, u.userStatus
				FROM parent_child pc
				LEFT JOIN profiles p ON p.profile_id = pc.p_id
				LEFT JOIN users u ON u.id = pc.user_id
				";

		if($id){
			$sql .= "WHERE u.id = ? ";
			$res = $this->db->query($sql, array($id));
		}else{
			$sql .= "ORDER BY p.lastname LIMIT {$limit},{$start}";
			$res = $this->db->query($sql);
		}
		// vd($this->db->last_query());
		if($res->num_rows()>=1)
		{
			foreach($res->result() as $k => $v)
			{
				$search[$k]['login_name'] = $v->username;
				$search[$k]['login_id'] = $v->user_id;
				$search[$k]['status'] = $v->userStatus;
				$search[$k]['children'] = $this->_get_parent_login($v->user_id);
			}


			return $search;
		}else{
			return FALSE;			
		}
		
	/*
		$sql = "SELECT * 
				  FROM users u
				  WHERE userType = ? ";
		$param[] = 'user';
		if($id){
			$sql .= " AND id = ? ";
			$param[] = $id;
		}else{
			$sql .= " LIMIT {$limit},{$start}";
		}

		$ret = $this->db->query($sql, $param);
		// vd($this->db->last_query());
		if($ret->num_rows()>=1)
		{
			foreach($ret->result() as $k => $v)
			{
				$search[$k]['login_name'] = $v->username;
				$search[$k]['login_id'] = $v->id;
				$search[$k]['status'] = $v->userStatus;
				$search[$k]['children'] = $this->_get_parent_login($v->id);
			}


			return $search;
		}else{
			return FALSE;			
		}
	*/
	}

	public function _get_parent_login($id)
	{
		$sql = 'SELECT concat_ws("",p.lastname," , ",p.firstname," ",p.middlename) as fullname,
							pc.id as pc_id
				  FROM parent_child pc
				  LEFT JOIN profiles p ON p.profile_id = pc.p_id
				  WHERE pc.user_id = ?';
		$ret = $this->db->query($sql,[$id]);

		return $ret->num_rows() >=1 ? $ret->result() : FALSE;
	}

	public function delete_student_from_login($id)
	{
		$this->db->where('id',$id)->delete('parent_child');
		return $this->db->affected_rows() >=1 ? TRUE :FALSE;
	}

	public function delete_login($id)
	{

		$this->db->where('id',$id)->delete('users');
		if($this->db->affected_rows() >=1)
		{
			$check = $this->db->where('user_id',$id)->get('parent_child');

			if($check->num_rows() >=1)
			{
				$this->db->where('user_id',$id)->delete('parent_child');
				return $this->db->affected_rows() >=1 ? TRUE :FALSE;
			}else{
				return TRUE;
			}
		}else{
			return FALSE;
		}
	}

	public function on_off_login($id,$type)
	{
		$stat = $type == 'enable' ? 'active' : 'inactive';
		$this->db->set('userStatus',$stat)->where('id',$id)->update('users');
		return $this->db->affected_rows() >=1 ? TRUE :FALSE;
	}

	public function autogenerate_parentlogin($array_of_student_e_ids = '')
	{
		$random_username = 'parent_'.time();
		$random_password = $this->randomString(rand(4,6));



		$e_ids = "'".implode("','",$array_of_student_e_ids)."'";
		
		$select = 'SELECT user_id FROM parent_child WHERE e_id IN ('.$e_ids.') group by user_id';


		$check = $this->db->query($select);

		if($check->num_rows() >= 1)
		{
			$login['status'] = 2;
			return (object)$login;
		}else{
			$get_student_emails = 'SELECT DISTINCT(email)
										  FROM enrollments e
										  LEFT JOIN profiles p ON e.e_profile_id = p.profile_id
										  WHERE e.e_id IN ('.$e_ids.')';
			
			$emails = $this->db->query($get_student_emails);
			$emailers = $this->db->query($get_student_emails);
			$emailer = $emailers->row();
			$random_username = $emailer->email ? $emailer->email :'';

			/*================
				1) create user
			==================*/
			if($random_username==''){
				log_message('e','Unable to create parent login account due to missing email address.');
				$login['status'] = FALSE;
				return (object)$login;
			}else{
			$user['username'] = $random_username;
			$user['hashed_password'] = $this->hash_password($random_password);
			$user['userType'] = 'user';
			$user['userStatus'] = 'active';
			$user['created_at'] = NOW;

			$this->db->insert('users',$user);

			if($this->db->affected_rows() >= 1)
			{
				$user_id = $this->db->insert_id();

			/*===============================================
				2) insert user with child in parent_child table
			=================================================*/

				foreach ($array_of_student_e_ids as $aosei_key => $aosei_id) 
				{
					$result = $this->_specific('enrollments','e_profile_id',['e_id'=>$aosei_id],TRUE);
						
					$profile_id = $result == FALSE ? 0 : $result->e_profile_id;

					$parent_child[$aosei_key]['e_id'] = $aosei_id;
					$parent_child[$aosei_key]['p_id'] = $profile_id;
					$parent_child[$aosei_key]['ay_id'] = $this->c_sy->id;
					$parent_child[$aosei_key]['user_id'] = $user_id;
				}

				$this->db->insert_batch('parent_child',$parent_child);
				if($this->db->affected_rows() >=1)
				{
			/* ===================
				3) return as object we will send email on the controller
			======================*/

					$login['status'] = TRUE;
					$login['user']['_useremails'] = $emails->result();
					$login['user']['_username'] = $random_username;
					$login['user']['_password'] = $random_password;

					return (object)$login;
				}else{
					log_message('e','Unable to insert parent child on database.');
					$login['status'] = FALSE;
					return (object)$login;
				}
			}else{
				$login['status'] = FALSE;
				return (object)$login;
			}
			}
		}
		
		
		//email parent username/password
		return FALSE;
	}
	
	//all parents log in creation
	public function resend_parentlogin($u_ids = '')
	{
		$u_id = $u_ids[0];
		//$random_username = 'parent_'.time();
		$random_password = $this->randomString(rand(4,6));
		//vd($u_id[0]);
		
		$sql = 'SELECT *
				  FROM users
				  WHERE id = ?';
		$check = $this->db->query($sql,[$u_id]);
		
		if($check->num_rows() >= 1)
		{
			$emailer = $check->row();

			/*================
				1) update user
			==================*/
			
			//$user['username'] = $emailer->username;
			$user['hashed_password'] = $this->hash_password($random_password);
			//$user['userType'] = 'user';
			$user['userStatus'] = 'active';
			$user['updated_at'] = NOW;

			$this->db->where('id', $u_id);
			$this->db->update('users', $user); 

			if($this->db->affected_rows() >= 1)
			{

				$login['status'] = TRUE;
				$login['user']['_useremails'] = $emailer->username;
				$login['user']['_username'] = $emailer->username;
				$login['user']['_password'] = $random_password;

				
				return (object)$login;
				
			}else{
				$login['status'] = FALSE;
				return (object)$login;
			}
			
		}else{
			return FALSE;
		}
		
		//email parent username/password
		return FALSE;
	}
	
	private function randomString($length = 8) 
	{
		// Select which type of characters you want in your random string
		$salt = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
		$rand = '';
		$i = 0;

		while ($i < $length) 
		{ // Loop until you have met the length
			$num = rand() % strlen($salt);
			$tmp = substr($salt, $num, 1);
			$rand = $rand . $tmp;
			$i++;
		}
		return $rand;
	}

	public function change_employee_user_password_by_emp_id($password,$emp_id)
	{
		$user_id = $this->db->select('id')
				 ->where('emp_id',$emp_id)
				 ->where('userStatus','active')
				 ->get('employees');

		if($user_id->num_rows() >=1)
		{
			$id = $user_id->row()->id;
			return $this->change_pass($password['pass'],$id);

		}else{
			return FALSE;
		}


	}

	/** UPDATE USERS PASSWORD
	 * @user_id Users ID
	 * @password Password String
	 */
	public function udpate_users_passwod($user_id = false, $password = false)
	{
		if($password && $user_id){

			$data = array(
               'hashed_password' => $this->hash_password(trim($password)),
               'updated_at' => NOW
            );

			$this->db->where('id', $user_id);
			$this->db->update('users', $data);

			$this->load->model('M_enrollees');

			if($this->db->affected_rows() > 0){

				$this->M_enrollees->_update_to_username_password_table($user_id, $password);

				return true;

			}

			return false;
		}

		return false;
	}
	
	public function insert_users_passwod($user_id = false, $password = false, $profile_id = false)
	{
		if($password){

			$data = array(
				'username' => $password,
				'hashed_password' => $this->hash_password(trim($password)),
				'userType' => 'student',
				'userStatus' => 'active',
				'created_at' => NOW
            );

			$this->db->insert('users', $data); 
			
			$user_id = $this->db->insert_id();
		
			$pdata = array(
				'user_id' => $user_id,
            );
			$this->db->where('profile_id', $profile_id);
			$this->db->update('profiles', $pdata);

			$this->load->model('M_enrollees');

			if($this->db->affected_rows() > 0){

				$this->M_enrollees->_update_to_username_password_table($user_id, $password);

				return true;

			}

			return false;
		}

		return false;
	}
	
}
?>